<template>
  <view class="address-edit-page">
    <!-- 地址表单 -->
    <view class="address-form">
      <view class="form-item">
        <view class="form-label required">收货人</view>
        <up-input 
          v-model="form.name" 
          placeholder="请输入收货人姓名" 
          border="none"
          class="form-input"
        />
      </view>
      
      <view class="form-item">
        <view class="form-label required">手机号</view>
        <up-input 
          v-model="form.phone" 
          placeholder="请输入手机号" 
          border="none"
          type="number"
          class="form-input"
        />
      </view>
      
      <view class="form-item" @click="showRegionPicker = true">
        <view class="form-label required">所在地区</view>
        <view class="region-selector">
          <text v-if="regionText" class="region-text">{{ regionText }}</text>
          <text v-else class="region-placeholder">请选择所在地区</text>
          <up-icon name="arrow-right" size="14" color="#ccc"></up-icon>
        </view>
      </view>
      
      <view class="form-item">
        <view class="form-label required">详细地址</view>
        <up-textarea 
          v-model="form.address" 
          placeholder="请输入详细地址，如道路、门牌号、小区、楼栋号、单元室等" 
          border="none"
          auto-height
          class="form-textarea"
        />
      </view>
      
      <view class="form-item switch-item">
        <view class="form-label">设为默认地址</view>
        <!-- 修复 switch 组件的使用方式 -->
        <up-switch 
          :modelValue="form.isDefault" 
          @update:modelValue="val => form.isDefault = val"
          activeColor="#ff6b35" 
          size="20"
        ></up-switch>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="save-btn">
      <up-button 
        type="primary" 
        shape="circle" 
        text="保存地址"
        @click="saveAddress"
        :loading="isSaving"
      ></up-button>
    </view>

    <!-- 地区选择器 -->
    <up-picker
      mode="region"
      :show="showRegionPicker"
      @close="showRegionPicker = false"
      @confirm="regionConfirm"
      @cancel="showRegionPicker = false"
    ></up-picker>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'

const showRegionPicker = ref(false)
const isSaving = ref(false)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  phone: '',
  province: '',
  city: '',
  area: '',
  address: '',
  isDefault: false
})

// 是否为编辑模式
const isEdit = ref(false)

// 地区文本显示
const regionText = computed(() => {
  if (form.province && form.city && form.area) {
    return `${form.province} ${form.city} ${form.area}`
  }
  return ''
})

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 地区选择确认
const regionConfirm = (e) => {
  const { province, city, area } = e.data
  form.province = province.label
  form.city = city.label
  form.area = area.label
}

// 保存地址
const saveAddress = () => {
  // 表单验证
  if (!form.name) {
    uni.showToast({
      title: '请输入收货人姓名',
      icon: 'none'
    })
    return
  }
  
  if (!form.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  
  // 手机号格式验证
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(form.phone)) {
    uni.showToast({
      title: '手机号格式不正确',
      icon: 'none'
    })
    return
  }
  
  if (!form.province || !form.city || !form.area) {
    uni.showToast({
      title: '请选择所在地区',
      icon: 'none'
    })
    return
  }
  
  if (!form.address) {
    uni.showToast({
      title: '请输入详细地址',
      icon: 'none'
    })
    return
  }
  
  // 保存地址
  saveAddressData()
}

// 保存地址数据
const saveAddressData = () => {
  isSaving.value = true
  
  try {
    // 获取现有的地址列表
    let addresses = uni.getStorageSync('userAddresses') || []
    
    if (isEdit.value) {
      // 编辑模式，更新现有地址
      const index = addresses.findIndex(item => item.id === form.id)
      if (index !== -1) {
        addresses[index] = { ...form }
      }
    } else {
      // 新增模式，生成ID并添加到列表
      const newAddress = {
        ...form,
        id: 'addr_' + Date.now()
      }
      
      // 如果设为默认地址，需要取消其他地址的默认状态
      if (newAddress.isDefault) {
        addresses = addresses.map(item => ({
          ...item,
          isDefault: false
        }))
      }
      
      addresses.unshift(newAddress)
    }
    
    // 保存到本地存储
    uni.setStorageSync('userAddresses', addresses)
    
    // 通知地址列表页面更新
    uni.$emit('addressUpdated')
    
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    })
    
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
  } catch (error) {
    console.error('保存地址失败:', error)
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    })
  } finally {
    isSaving.value = false
  }
}

// 获取地址详情（编辑模式）
const getAddressDetail = (id) => {
  try {
    const addresses = uni.getStorageSync('userAddresses') || []
    const address = addresses.find(item => item.id === id)
    if (address) {
      Object.assign(form, address)
      isEdit.value = true
    }
  } catch (error) {
    console.error('获取地址详情失败:', error)
  }
}

// 页面加载
onLoad((options) => {
  if (options.id) {
    getAddressDetail(options.id)
  }
})
</script>

<style lang="scss" scoped>
.address-edit-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .nav-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    background-color: #fff;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 1rpx;
      background-color: #eee;
    }
    
    .nav-back {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .nav-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .nav-placeholder {
      width: 40rpx;
    }
  }
  
  .address-form {
    background-color: #fff;
    margin-top: 20rpx;
    
    .form-item {
      padding: 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .form-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
        
        &.required::before {
          content: '*';
          color: #ff6b35;
          margin-right: 10rpx;
        }
      }
      
      .form-input {
        padding: 0;
      }
      
      .region-selector {
        display: flex;
        align-items: center;
        justify-content: space-between;
        min-height: 40rpx;
        
        .region-text {
          font-size: 28rpx;
          color: #333;
        }
        
        .region-placeholder {
          font-size: 28rpx;
          color: #999;
        }
      }
      
      .form-textarea {
        padding: 0;
      }
      
      &.switch-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }
  
  .save-btn {
    padding: 40rpx 30rpx;
  }
}
</style>